package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.CosConstantProperties;
import com.atguigu.tingshu.album.manager.CosManager;
import com.atguigu.tingshu.album.manager.VodManager;
import com.atguigu.tingshu.album.service.FileUploadService;
import com.atguigu.tingshu.common.execption.BusinessException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.utils.ThrowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Objects;

@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private CosManager cosManager;

    @Autowired
    private VodManager vodManager;

    @Autowired
    private CosConstantProperties cosConstantProperties;

    private static final Integer MAX_FILE_SIZE = 1024 * 1024 * 5;

    /**
     * 描述：上传文件
     *
     * @param file
     * @return boolean
     * @author daiyuling
     * @date 2025/10/22
     */
    @Override
    public String upload(MultipartFile file) {
        log.info("上传文件开始");
        //校验文件  大小  // 类型
        ThrowUtil.throwIf(file.isEmpty(), ResultCodeEnum.DATA_ERROR, "文件不能为空");
        ThrowUtil.throwIf(file.getSize() > MAX_FILE_SIZE, ResultCodeEnum.DATA_ERROR, "文件大小不能超过5MB");
        String originalFilename = file.getOriginalFilename();
        ThrowUtil.throwIf(originalFilename == null, ResultCodeEnum.DATA_ERROR, "文件名称不能为空");
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        ThrowUtil.throwIf(!cosConstantProperties.getFileType().contains(fileType), ResultCodeEnum.DATA_ERROR, "文件类型不支持");

        try {
            // 生成文件存储的key
            String key = "album/" + originalFilename;
            // 创建临时文件
            File tempFile = new File(System.getProperty("java.io.tmpdir"), Objects.requireNonNull(originalFilename));
            file.transferTo(tempFile);
            // 如果是图片文件，则进行图片审核
            if (Objects.requireNonNull(file.getContentType()).startsWith("image") && !vodManager.checkImgContent(tempFile)) {
                throw new BusinessException(ResultCodeEnum.DATA_ERROR, "图片内容审核失败");
            }
            // 上传文件到COS
            String url = cosManager.putObject(key, tempFile);
            // 删除临时文件
            boolean delete = tempFile.delete();
            if (!delete) {
                log.warn("文件删除失败:{}", tempFile.getAbsolutePath());
            }
            // 返回文件路径
            return url;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return null;
        }
    }
}
